package cn.edu.hitsz.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import cn.edu.hitsz.conf.DatabaseConfig;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

/**
 * DATA SERIALIZED INTO LOCAL DATABASE ACCORDING TO THE DATABSECONFIG DATACONFIG
 * IS THE BASE DATABASE CONFIGUARTION CLASS MAP<STRING,STRING> IS THE DATA OT
 * INSERT INTO LOCAL DATABASE
 * 
 * @author mingchen
 * @date 2015年8月9日
 */
public class DatabaseConnection extends Connection {

	private static final Logger log= Logger.getLogger(DatabaseConnection.class);

	private final DatabaseConfig dbcnf;
	private  Map<String, String> map;

	/**
	 * 
	 * Constructor function of Class
	 * 
	 * @param dbcnf
	 * @param map
	 */
	public DatabaseConnection(DatabaseConfig dbcnf, Map<String, String> map) {
		this.dbcnf = dbcnf;
		this.map = map;
	}

	public DatabaseConnection(DatabaseConfig dbcnf) {
		this.dbcnf = dbcnf;
		map = null;
	}

	/**
	 * Set the map to the connection
	 * 
	 * @param map
	 *            void 2015年8月17日下午2:49:18
	 */
	@Override
	public void setMap(Map<String,String> map){
		this.map = map;
	}

	/**
	 * Offer the map data to the connection and pipeline to the local Mongo
	 * Database
	 * 
	 * @param map
	 *            void 2015年8月17日下午2:53:39
	 */
	@Override
	public boolean offerData(Map<String, String> map) {
		this.map = map;
		write();
		return true;
	}
	/**
	 * The method from interface Connetcion
	 */
	@Override
	public void write() {
		MongoClient mongo = null;
		try{
			String url = String.format("mongodb://%s:%s@%s:%d/%s",
					dbcnf.getUserName(), dbcnf.getUserPwd(), dbcnf.getHost(),
					dbcnf.getPort(), "admin");
			url = url.replaceAll("\"", "");
			MongoClientURI mur = new MongoClientURI(url);
			mongo = new MongoClient(mur);
			log.info("Connetion to mongo database server");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (mongo == null) {
			System.out.println("MOngo nulll");
		}
		DB db = mongo.getDB("spider");
		DBCollection mc = db.getCollection("page");
		List<DBObject> list = new ArrayList<DBObject>();
		log.info("Load data to mongo databse");
		for (String key : map.keySet()) {
			DBObject doc = new BasicDBObject();
			doc.put("title", key);
			doc.put("content", map.get(key));
			list.add(doc);
		}
		mc.insert(list);
		mongo.close();
		log.info("Write data done !["+map.size()+"] rows affected.");
	}

}
